package com.company.test16;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * Created by Administrator on 2016.8.3.
 */
public class Test1609 extends JFrame {
    MyPanel panel=new MyPanel();
    public Test1609(){

        panel.setFocusable(true);
        panel.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                super.keyPressed(e);
                Graphics g=getGraphics();

                switch (e.getKeyCode()){
                    case KeyEvent.VK_DOWN:panel.myPaintComponent(g,panel.x,panel.y+20);break;
                    case KeyEvent.VK_UP:panel.myPaintComponent(g,panel.x,panel.y-20);break;
                    case KeyEvent.VK_LEFT:panel.myPaintComponent(g,panel.x-20,panel.y);break;
                    case KeyEvent.VK_RIGHT:panel.myPaintComponent(g,panel.x+20,panel.y);break;
                }
            }
        });

        this.add(panel);
    }

    private class MyPanel extends JPanel{
        int x;
        int y;

        public MyPanel(){
            x=150;
            y=150;
        }

        protected void myPaintComponent(Graphics g,int x,int y){
            g.drawLine(this.x,this.y,x,y);
            this.x=x;
            this.y=y;
        }
    }
}
